<?php

namespace App\Services;

use App\Models\Crm_Agency_Auth;
use App\Third\Acsign\Acsing;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

class SystemService
{
    public function agencyAuthList($params)
    {
        return Crm_Agency_Auth::getFilter($params)
            ->select(['id','name','code','idcard','mobile','contacts'])
            ->Status()
            ->get();
    }

    public function agencyAuthAdd($params)
    {
        $asignInstance = new Acsing();
        $result = $asignInstance->authCompanyIdentifyUrl();
        if($result['rt']){
            try {
                // 开始数据库事务
                DB::beginTransaction();
                $res = Crm_Agency_Auth::create([
                    'agencyid' => $params['aid'],
                    'serialno' => $result['data']['serialNo'],
                    'status' => $result['data']['result'],
                ]);
                if(!$res){
                    throw new \Exception("创建Crm_Agency_Auth企业认证失败");
                }
                DB::commit();
                return ['code' => 200,'status' => $result['data']];
            }catch (Throwable $e) {
                // 如果在事务执行过程中发生异常，则回滚事务
                DB::rollBack();
                // 记录日志或处理错误
                Log::error("Database transaction failed: " . $e->getMessage());
                return ['code' => 400,'status' => false];
            }
        }else{
            return ['code' => 1012,'status' => false];
        }
    }

    public function agencyAuthNotify($params)
    {
        if($params['result'] == 1){
            //实名认证信息查询
            $asignInstance = new Acsing();
            $result = $asignInstance->getAuthRecordInfo($params);
            if($result['rt']){
                $res = Crm_Agency_Auth::where('serialno',$params['serialNo'])->first();
                $res->contacts = $result['data']['realName'];
                $res->idcard = $result['data']['idCardNo'];
                $res->code = $result['data']['creditCode'];
                $res->mobile = $result['data']['agentMobile'];
                $res->name = $result['data']['companyName'];
                $res->status = $result['data']['result'];
                $res->save();

                $resultUser = $asignInstance->getCompUser(md5($result['data']['creditCode']));

                if(!$resultUser['rt'] || empty($enterprisesult['data'])){
                    $asignInstance->addEnterpriseUser(md5($result['data']['creditCode']), '', '', $result['data']['realName'], $result['data']['idCardNo'], '', $result['data']['agentMobile'], '', '', '', 1);
                }
            }


        }

    }
}
